package com.crm.controller;

import com.crm.commons.UserDto;
import com.crm.commons.domain.ResponseData;
import com.crm.entity.CrmUser;
import com.crm.service.ICrmUserService;
import com.crm.util.JwtTokenUtil;
import com.crm.vo.MySecurityUser;
import com.crm.vo.PageBean;
import com.crm.vo.SysUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author junxian,dou
 * @since 2024-11-25
 */
@RequestMapping("/user")
@Api(tags = "用户管理")
@RestController
public class CrmUserController extends BaseController  {


    private static final Logger log = LoggerFactory.getLogger(CrmUserController.class);
    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private ICrmUserService userService;

    @Resource
    private ObjectMapper objectMapper;


    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public ResponseData login2(@RequestBody UserDto user) throws JsonProcessingException {
        Authentication authenticationRequest =
                UsernamePasswordAuthenticationToken.unauthenticated(user.getUserName(), user.getPassWord());
        Authentication authentication = authenticationManager.authenticate(authenticationRequest);
        //从认证信息中获取登录用户信息
        MySecurityUser securityUser= (MySecurityUser) authentication.getPrincipal();
        CrmUser sysUser = securityUser.getSysUser();
        String strUserInfo = objectMapper.writeValueAsString(sysUser);
        //获取用户的权限信息
        List<SimpleGrantedAuthority> authorities = (List<SimpleGrantedAuthority>) securityUser.getAuthorities();
        // collect 收集
        List<String> authList=authorities.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.toList());
        //生成jwt
        String jwtToken = JwtTokenUtil.createJwt(strUserInfo, authList);
        return ResponseData.success(jwtToken);
    }


    @PostMapping("/add")
    @ApiOperation(value = "创建用户")
    @PreAuthorize("hasAuthority('system:user:add')")
    public ResponseData add(@RequestBody UserDto user ){
        userService.saveUserDetails(user,getUserInfo());
        return ResponseData.success();
    }

    @GetMapping("/info")
    @ApiOperation(value = "获取用户信息")
    public ResponseData getInfo(){
        return ResponseData.success(getUserInfo());
    }

    @PostMapping("/uploadImage")
    @ApiOperation(value = "上传头像")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public ResponseData uploadImage(MultipartFile file){
        return ResponseData.success(userService.uploadImage(file));
    }


    /**
     * 修改用户头像
     * @param userInfo
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "保存头像信息")
    @PostMapping("/updateAvatar")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public ResponseData updateAvatar(@RequestBody CrmUser userInfo)throws Exception{
        userService.updateAvatar(userInfo);
       return ResponseData.success();
    }

    /**
     * 修改用户邮箱
     * @param userInfo
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "修改邮箱")
    @PostMapping("/updateEmail")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public ResponseData updateEmail(@RequestBody CrmUser userInfo)throws Exception{
        userService.updateEmail(userInfo);
        return ResponseData.success();
    }


    /**
     * 修改密码
     * @param sysUser
     * @return
     */
    @ApiOperation(value = "修改密码")
    @PostMapping("/updateUserPwd")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public ResponseData updateUserPwd(@RequestBody SysUser sysUser){
        return userService.updatePassWord(sysUser);
    }

    /**
     * 根据条件分页查询用户信息
     * @param pageBean
     * @return
     */
    @ApiOperation(value = "根据条件分页查询用户信息")
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:user:query')")
    public ResponseData list(@RequestBody PageBean pageBean){
        PageBean resultMap= userService.selectUserList(pageBean);
        return ResponseData.success(resultMap);
    }

    /**
     * 根据id查询
     * @param id
     * @return ResponseData
     */
    @ApiOperation(value = "根据条件分根据id页查询用户信息")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:query')")
    public ResponseData findById(@PathVariable(value = "id")String id){

        UserDto byId = userService.getInfoById(id);
        return ResponseData.success(byId);
    }

    /**
     * 验证用户名
     * @param sysUser
     * @return
     */
    @ApiOperation(value = "验证用户名")
    @PostMapping("/checkUserName")
    @PreAuthorize("hasAuthority('system:user:query')")
    public ResponseData checkUserName(@RequestBody UserDto sysUser){
        if(userService.getByUsername(sysUser.getUserName())== 0){
            return ResponseData.success();
        }else{
            return ResponseData.error("用户名已存在");
        }
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除用户")
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:user:delete')")
    public ResponseData delete(@RequestBody String[] ids) {
        userService.deleteByUserId(ids);
        return ResponseData.success();
    }

    /**
     * 重置密码
     * @param id
     * @return
     */
    @ApiOperation(value = "重置密码")
    @GetMapping("/resetPassword/{id}")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public ResponseData resetPassword(@PathVariable(value = "id")String id) {
        userService.resetPassWord(id);
        return ResponseData.success();
    }

    /**
     * 更新status状态
     * @param id
     * @param status
     * @return
     */
    @ApiOperation(value = "更新status状态")
    @GetMapping("/updateStatus/{id}/status/{status}")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public ResponseData updateStatus(@PathVariable(value = "id")String id,@PathVariable(value
            = "status")String status) {

        userService.updateStatus(id,status);
        return ResponseData.success();
    }

    /**
     * 用户角色授权
     * @param userId
     * @param roleIds
     * @return
     */
    @ApiOperation(value = "用户角色授权")
    @PostMapping("/grantRole/{userId}")
    @PreAuthorize("hasAuthority('system:user:role')")
    public ResponseData grantRole(@PathVariable("userId") String userId,@RequestBody Long[]
            roleIds) {
        userService.grantRole(userId,roleIds);
        return ResponseData.success();
    }

    @ApiOperation(value = "用户角色授权")
    @GetMapping("/ownerList")
    public ResponseData getOwnerList() {
     List<CrmUser> list = userService.getOwnerList();
        return ResponseData.success(list);
    }
}
